import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Observable } from "rxjs";
import { ROLES_KEY } from "../decorators/role.decorators";
import { Role } from "../enum/roles.enum";
import { UserService } from "../user/user.service";

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private userService: UserService,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // jwt -> userId -> user -> roles
    // getAllAndMerge -> 合并
    // getAllAndOverride -> 路由上的 metadata 会覆盖 controller 上的
    const requiredRoles = this.reflector.getAllAndMerge<Role[]>(ROLES_KEY, [context.getHandler(), context.getClass()]);
    console.log("requiredRoles ————》", requiredRoles);
    if (!requiredRoles || (Array.isArray(requiredRoles) && requiredRoles.length === 0)) {
      return true;
    }

    const req = context.switchToHttp().getRequest();
    const user = await this.userService.find(req.user.username);
    console.log("user ————》", user);

    const roleIds = user!.roles.map((role) => role.id);

    const flag = requiredRoles.some((role) => roleIds.includes(role));
    return flag;
  }
}
